package simple;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 异步发送
 */
public class AsyncProducer {
    public static void main(String[] args) throws Exception{
        DefaultMQProducer producer = new DefaultMQProducer("syncProducer");
        producer.setNamesrvAddr("192.168.1.153:9876");
        producer.start();
        final CountDownLatch downLatch = new CountDownLatch(100);
        for (int i=0; i<100; i++) {
            Message message = new Message("simple", "tag2", "异步发送".getBytes(StandardCharsets.UTF_8));
            final int finalI = i;
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    downLatch.countDown();
                    System.out.println(finalI +"消息发送成功"+sendResult);
                }

                @Override
                public void onException(Throwable throwable) {
                    downLatch.countDown();
                    System.out.println(finalI+"消息发送失败"+throwable.getMessage());
                }
            });
        }
        downLatch.await(5, TimeUnit.SECONDS);
        producer.shutdown();
        System.out.println("发送者关闭");
    }
}
